package org.ofbiz.wvtools;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom.JDOMException;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceUtil;
import org.ofbiz.wvtools.wxutil.GzhConfig;
import org.ofbiz.wvtools.wxutil.RequestHandler;
import org.ofbiz.wvtools.wxutil.Sha1Util;
import org.ofbiz.wvtools.wxutil.XMLUtil;

import com.alibaba.fastjson.JSON;


public class CoAccountServices {
	private static final String module = CoAccountServices.class.getName();
	
	
	public static GenericValue getFinanceCoAccount(Delegator delegator,String partyId) throws GenericEntityException{
		Debug.log("partyId = "+partyId);
		//金融账户
		List<GenericValue> accountList = delegator.findByAnd("CoAccount", UtilMisc.toMap("partyId",partyId,"accountTypeId", "FINANCE_TYPE"), null, false);
		GenericValue coAccount =EntityUtil.getFirst(accountList);
		String accountId= coAccount.getString("accountId");
		BigDecimal totalAmount= coAccount.getBigDecimal("totalAmount");
		BigDecimal availableAmount= coAccount.getBigDecimal("availableAmount");
		BigDecimal freezeAmount= coAccount.getBigDecimal("freezeAmount");
	    
		Debug.log("accountId = "+accountId+" totalAmount = "+totalAmount
				+" availableAmount = "+availableAmount+" freezeAmount = "+freezeAmount);
		return coAccount;
	}
	
	
	public static Map<String, Object> getCoAccountWebPrepay(DispatchContext ctx, Map<String, ? extends Object> context) {
		Debug.log("createEcOrder   === start");
		Map<String, Object> result = ServiceUtil.returnSuccess();
		Delegator delegator = ctx.getDelegator();
		String historyId = (String)context.get("historyId");
		HttpServletRequest request = (HttpServletRequest)context.get("request");
		HttpServletResponse response = (HttpServletResponse)context.get("response");
		String noncestr = Sha1Util.getNonceStr();
		try {
			//付款金额
			String total_fee = "";
			String order_price = "";
			//产品ID 以及类型
			String product_name="";
			GenericValue accountHistory = delegator.findOne("CoAccountHistory", UtilMisc.toMap("historyId", historyId),false);
			total_fee = String.valueOf(accountHistory.getBigDecimal("amount").doubleValue()*100);
			if(total_fee.contains(".")){
				order_price = total_fee.substring(0, total_fee.indexOf("."));
			}else{
				order_price = total_fee;
			}
			product_name = historyId;
			GzhConfig config = new GzhConfig("");	
			
			RequestHandler reqHandler = new RequestHandler(request, response);
			 //初始化 
			reqHandler.init();
			reqHandler.init(config.APPID, config.APPSECRET, config.KEY, "");
			//执行统一下单接口 获得预支付id
			reqHandler.setParameter("appid",config.APPID);
			reqHandler.setParameter("mch_id", config.MCHID);                //商户号
			reqHandler.setParameter("nonce_str", noncestr);            //随机字符串
			if(product_name.length() > 30){
				product_name = product_name.substring(0, 30) + "..";
			}
			reqHandler.setParameter("body", product_name);                        //商品描述
			reqHandler.setParameter("out_trade_no", historyId);        //商家订单号
			reqHandler.setParameter("total_fee", order_price);                    //商品金额,以分为单位
			reqHandler.setParameter("spbill_create_ip",request.getRemoteAddr());   //用户的公网ip  IpAddressUtil.getIpAddr(request)
			//下面的notify_url是用户支付成功后为微信调用的action
			reqHandler.setParameter("notify_url", config.WEB_NOTIFY_URL);
			reqHandler.setParameter("trade_type", "NATIVE");
			//订单开始
			Date now=new Date();
		    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		    String time_start=dateFormat.format(now);
			reqHandler.setParameter("time_start", time_start);
			//订单结束时间
			String time_expire= getHalfHourAgoTime(5,"yyyyMMddHHmmss");
			reqHandler.setParameter("time_expire", time_expire);
			
			//------------需要进行用户授权获取用户openid-------------
			String requestUrl = reqHandler.getRequestURL("");
			Debug.log("requestUrl==================="+requestUrl);
			//统一下单接口提交  xml格式
			URL orderUrl = new URL("https://api.mch.weixin.qq.com/pay/unifiedorder");
			HttpURLConnection conn = (HttpURLConnection) orderUrl.openConnection();
			conn.setConnectTimeout(30000); // 设置连接主机超时（单位：毫秒)
			conn.setReadTimeout(30000); // 设置从主机读取数据超时（单位：毫秒)
			conn.setDoOutput(true); // post请求参数要放在http正文内，顾设置成true，默认是false
			conn.setDoInput(true); // 设置是否从httpUrlConnection读入，默认情况下是true
			conn.setUseCaches(false); // Post 请求不能使用缓存
			// 设定传送的内容类型是可序列化的java对象(如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
			conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			conn.setRequestMethod("POST");// 设定请求的方法为"POST"，默认是GET
			conn.setRequestProperty("Content-Length",requestUrl.length()+"");
			String encode = "utf-8";
			OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), encode);
			out.write(requestUrl.toString());
			out.flush();
			out.close();
			String json = getOut(conn);
			Debug.log("result=========返回的xml============="+json);
			Map<String, String> orderMap = XMLUtil.doXMLParse(json);
			
			Debug.log("orderMap==========================="+orderMap);
			//得到的预支付id
			String prepay_id = orderMap.get("prepay_id");
			String code_url = orderMap.get("code_url");
			result.put("historyId", historyId);
			result.put("code_url", code_url);
			Debug.log("prepay_id====="+prepay_id);	
			Debug.log("code_url====="+code_url);	
			} catch (UnsupportedEncodingException e) {
				Debug.logError(e.getMessage(), module);
			} catch (Exception e) {
				Debug.logError(e.getMessage(), module);
			}
		return result;
	}
	
	public static Map<String, Object> getCoAccountPrepay(DispatchContext ctx, Map<String, ? extends Object> context) {
		Debug.log("createEcOrder   === start");
		Map<String, Object> result = ServiceUtil.returnSuccess();
		Delegator delegator = ctx.getDelegator();
		String historyId = (String)context.get("historyId");
		String code = (String)context.get("code");
		HttpServletRequest request = (HttpServletRequest)context.get("request");
		HttpServletResponse response = (HttpServletResponse)context.get("response");
		//timeStamp  nonceStr  package  signType
		String timestamp = Sha1Util.getTimeStamp();
		String noncestr = Sha1Util.getNonceStr();
		try {
			//付款金额
			String total_fee = "";
			String order_price = "";
			//产品ID 以及类型
			String product_name="";
			GenericValue accountHistory = delegator.findOne("CoAccountHistory", UtilMisc.toMap("historyId", historyId),false);
			GenericValue account = delegator.findOne("CoAccount", UtilMisc.toMap("historyId", accountHistory.getString("accountId")),false);
			total_fee = String.valueOf(accountHistory.getBigDecimal("amount").doubleValue()*100);
			if(total_fee.contains(".")){
				order_price = total_fee.substring(0, total_fee.indexOf("."));
			}else{
				order_price = total_fee;
			}
			product_name = historyId;
			GzhConfig config = new GzhConfig("");	
			//获取openID
			String openid = "";
			if(UtilValidate.isNotEmpty(code)){
				String openParam = "appid="+config.APPID+"&secret="+config.APPSECRET+"&js_code="+code+"&grant_type=authorization_code";
				String openJsonStr = SendGET("https://api.weixin.qq.com/sns/jscode2session", openParam);
				Debug.log("openJsonStr==="+openJsonStr);
				Map<String,Object> openMap = JSON.parseObject(openJsonStr);
				openid = (String) openMap.get("openid");
			}else{
				GenericValue organ = delegator.findOne("Person", UtilMisc.toMap("partyId",account.getString("partyIdForm")), false);
				openid = organ.getString("weixinOpenId");
			}
			
			//String session_key = (String) openMap.get("session_key");
			RequestHandler reqHandler = new RequestHandler(request, response);
			 //初始化 
			reqHandler.init();
			reqHandler.init(config.APPID, config.APPSECRET, config.KEY, "");
			//执行统一下单接口 获得预支付id
			reqHandler.setParameter("appid",config.APPID);
			reqHandler.setParameter("mch_id", config.MCHID);                //商户号
			reqHandler.setParameter("nonce_str", noncestr);            //随机字符串
			if(product_name.length() > 30){
				product_name = product_name.substring(0, 30) + "..";
			}
			reqHandler.setParameter("body", product_name);                        //商品描述
			reqHandler.setParameter("out_trade_no", historyId);        //商家订单号
			reqHandler.setParameter("total_fee", order_price);                    //商品金额,以分为单位
			reqHandler.setParameter("spbill_create_ip",request.getRemoteAddr());   //用户的公网ip  IpAddressUtil.getIpAddr(request)
			//下面的notify_url是用户支付成功后为微信调用的action
			reqHandler.setParameter("notify_url", config.NOTIFY_URL);//回调处理订单地址
			//reqHandler.setParameter("notify_url", "https://shop.cool-grid.com/weimall/control/weixinPay_notify");//回调处理订单地址
			reqHandler.setParameter("trade_type", "JSAPI");
			
			//订单开始时间
			Date now=new Date();
		    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		    String time_start=dateFormat.format(now);
			reqHandler.setParameter("time_start", time_start);
			//订单结束时间
			String time_expire= getHalfHourAgoTime(5,"yyyyMMddHHmmss");
			reqHandler.setParameter("time_expire", time_expire);
			
			//------------需要进行用户授权获取用户openid-------------
			reqHandler.setParameter("openid", openid);   
			String requestUrl = reqHandler.getRequestURL("");
			Debug.log("requestUrl==================="+requestUrl);
			//统一下单接口提交  xml格式
			URL orderUrl = new URL("https://api.mch.weixin.qq.com/pay/unifiedorder");
			HttpURLConnection conn = (HttpURLConnection) orderUrl.openConnection();
			conn.setConnectTimeout(30000); // 设置连接主机超时（单位：毫秒)
			conn.setReadTimeout(30000); // 设置从主机读取数据超时（单位：毫秒)
			conn.setDoOutput(true); // post请求参数要放在http正文内，顾设置成true，默认是false
			conn.setDoInput(true); // 设置是否从httpUrlConnection读入，默认情况下是true
			conn.setUseCaches(false); // Post 请求不能使用缓存
			// 设定传送的内容类型是可序列化的java对象(如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
			conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			conn.setRequestMethod("POST");// 设定请求的方法为"POST"，默认是GET
			conn.setRequestProperty("Content-Length",requestUrl.length()+"");
			String encode = "utf-8";
			OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), encode);
			out.write(requestUrl.toString());
			out.flush();
			out.close();
			String result1 = getOut(conn);
			Debug.log("result=========返回的xml============="+result1);
			Map<String, String> orderMap = XMLUtil.doXMLParse(result1);
			
			Debug.log("orderMap==========================="+orderMap);
			//得到的预支付id
			String prepay_id = orderMap.get("prepay_id");
			
			SortedMap<String,String> params = new TreeMap<String,String>();
	        params.put("appId", config.APPID);
	        params.put("timeStamp",timestamp);
	        params.put("nonceStr", noncestr);
	        params.put("package", "prepay_id="+prepay_id);
	        params.put("signType", "MD5");
	        
	        //生成支付签名
	        String paySign =  reqHandler.createSign(params,"");
			
	        result.put("timeStamp", timestamp);
	        result.put("nonceStr", noncestr);
	        result.put("package", "prepay_id="+prepay_id);
	        result.put("signType", "MD5");
	        result.put("paySign", paySign);
	        
		} catch (GenericEntityException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JDOMException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 异步返回
	 */
	public static String wxCoAccountNotify(HttpServletRequest request, HttpServletResponse response){
        try {
        	Delegator delegator = (Delegator) request.getAttribute("delegator");
        	LocalDispatcher dispatcher = (LocalDispatcher)request.getAttribute("dispatcher");
    		InputStream inStream = request.getInputStream();
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
			    outSteam.write(buffer, 0, len);
			}
			outSteam.close();
			inStream.close();
			String resultStr  = new String(outSteam.toByteArray(),"utf-8");
			Map<String, String> resultMap = XMLUtil.doXMLParse(resultStr);
			Debug.log("resultMap======================="+resultMap);
			String out_trade_no = resultMap.get("out_trade_no");
			String transaction_id = resultMap.get("transaction_id");
			String return_code = resultMap.get("return_code");
			GenericValue accountHistory = delegator.findOne("CoAccountHistory", UtilMisc.toMap("historyId", out_trade_no),false);
			String statusId = accountHistory.getString("statusId");
			if(return_code.equals("SUCCESS")){
				if(UtilValidate.isNotEmpty(accountHistory) && "WITH_APPLY".equals(statusId)){
					GenericValue userLogin = delegator.findOne("UserLogiin", UtilMisc.toMap("userLoginId", "admin"),false);
					dispatcher.runSync("setRechargeHistory", UtilMisc.toMap("historyId", out_trade_no,"statusId","WITH_END",
							"transactionId",transaction_id,"userLogin",userLogin));
				}
			}
			request.setAttribute("out_trade_no", out_trade_no);
			response.getWriter().write(RequestHandler.setXML("SUCCESS", ""));
		} catch (UnsupportedEncodingException e) { 
			Debug.logError(e.getMessage(), module);
		} catch (IOException e) {
			Debug.logError(e.getMessage(), module);
		} catch (JDOMException e) {
			Debug.logError(e.getMessage(), module);
		} catch (GenericEntityException e) {
			Debug.logError(e.getMessage(), module);
		} catch (GenericServiceException e) {
			Debug.logError(e.getMessage(), module);
		}
		return "success";
	}
	
	public static Map<String, Object> getWxApi(DispatchContext ctx, Map<String, ? extends Object> context) {
		Map<String, Object> result = ServiceUtil.returnSuccess();
		Delegator delegator = ctx.getDelegator();
		String orderId = (String)context.get("orderId");
		try {
			GenericValue orderHeader = null;
			if(!orderId.contains("PUR_")) {
				orderHeader = delegator.findOne("LetOrderHeader", UtilMisc.toMap("orderId", orderId),false);
			}else {
				orderHeader = delegator.findOne("LetPurchaseOrder", UtilMisc.toMap("orderId", orderId),false);
			}
			String productStoreId = orderHeader.getString("productStoreId");
			GzhConfig config = new GzhConfig(productStoreId);
			result.put("appId", config.APPID);
			result.put("mchId", config.MCHID);
			result.put("key", config.KEY);
			result.put("appSecret", config.APPSECRET);
		} catch (GenericEntityException e) {
			e.printStackTrace();
		}	
			
		return result;
	}
	
	
	public static Map<String, Object> getCoOrderPrepay(DispatchContext ctx, Map<String, ? extends Object> context) {
		Map<String, Object> result = ServiceUtil.returnSuccess();
		Delegator delegator = ctx.getDelegator();
		String orderId = (String)context.get("orderId");
		String code = (String)context.get("code");
		HttpServletRequest request = (HttpServletRequest)context.get("request");
		HttpServletResponse response = (HttpServletResponse)context.get("response");
		//timeStamp  nonceStr  package  signType
		String timestamp = Sha1Util.getTimeStamp();
		String noncestr = Sha1Util.getNonceStr();
		try {
			//付款金额
			String total_fee = "";
			String order_price = "";
			//产品ID 以及类型
			String product_name="";
			GenericValue orderHeader = null;
			if(!orderId.contains("PUR_")) {
				orderHeader = delegator.findOne("LetOrderHeader", UtilMisc.toMap("orderId", orderId),false);
			}else {
				orderHeader = delegator.findOne("LetPurchaseOrder", UtilMisc.toMap("orderId", orderId),false);
			}
			String productStoreId = orderHeader.getString("productStoreId");
			total_fee = String.valueOf(orderHeader.getBigDecimal("grandTotalAmount").doubleValue()*100);
			result.put("totalPrice", orderHeader.getBigDecimal("grandTotalAmount"));
			if(total_fee.contains(".")){
				order_price = total_fee.substring(0, total_fee.indexOf("."));
			}else{
				order_price = total_fee;
			}
			product_name = orderId;
			GzhConfig config = new GzhConfig(productStoreId);	
			//获取openID
			String openid = "";
			Debug.log("code==========="+code);
			GenericValue person = delegator.findOne("Person", UtilMisc.toMap("partyId",orderHeader.getString("customerId")), false);
			openid = person.getString("weixinOpenId");
			
			if(UtilValidate.isEmpty(openid)){
				String openParam = "appid="+config.APPID+"&secret="+config.APPSECRET+"&code="+code+"&grant_type=authorization_code";
				Debug.log("openParam============"+openParam);
				String openJsonStr = SendGET("https://api.weixin.qq.com/sns/oauth2/access_token", openParam);
				Debug.log("openJsonStr==="+openJsonStr);
				Map<String,Object> openMap = JSON.parseObject(openJsonStr);
				openid = (String) openMap.get("openid");
	            if(UtilValidate.isEmpty(openid)){
	                return ServiceUtil.returnError("获取openId失败!");
	            }
				person.set("weixinOpenId", openid);
				person.store();
			}else{
				openid = person.getString("weixinOpenId");
			}
			
			RequestHandler reqHandler = new RequestHandler(request, response);
			 //初始化 
			reqHandler.init();
			reqHandler.init(config.APPID, config.APPSECRET, config.KEY, "");
			//执行统一下单接口 获得预支付id
			reqHandler.setParameter("appid",config.APPID);
			reqHandler.setParameter("mch_id", config.MCHID);                //商户号
			reqHandler.setParameter("nonce_str", noncestr);            //随机字符串
			if(product_name.length() > 30){
				product_name = product_name.substring(0, 30) + "..";
			}
			reqHandler.setParameter("body", product_name);                        //商品描述
			reqHandler.setParameter("out_trade_no", orderId);        //商家订单号
			reqHandler.setParameter("total_fee", order_price);                    //商品金额,以分为单位
			reqHandler.setParameter("spbill_create_ip",request.getRemoteAddr());   //用户的公网ip  IpAddressUtil.getIpAddr(request)
			//下面的notify_url是用户支付成功后为微信调用的action
			reqHandler.setParameter("notify_url", config.NOTIFY_URL2);//回调处理订单地址
			//reqHandler.setParameter("notify_url", "https://shop.cool-grid.com/weimall/control/weixinPay_notify");//回调处理订单地址
			reqHandler.setParameter("trade_type", "JSAPI");
			
			//订单开始时间
			Date now=new Date();
		    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		    String time_start=dateFormat.format(now);
			reqHandler.setParameter("time_start", time_start);
			//订单结束时间
			String time_expire= getHalfHourAgoTime(5,"yyyyMMddHHmmss");
			reqHandler.setParameter("time_expire", time_expire);
			
			//------------需要进行用户授权获取用户openid-------------
			reqHandler.setParameter("openid", openid);   
			Debug.log("begin============begin====================");
			String requestUrl = reqHandler.getRequestURL(productStoreId);
			Debug.log("requestUrl==================="+requestUrl);
			//统一下单接口提交  xml格式
			URL orderUrl = new URL("https://api.mch.weixin.qq.com/pay/unifiedorder");
			HttpURLConnection conn = (HttpURLConnection) orderUrl.openConnection();
			conn.setConnectTimeout(30000); // 设置连接主机超时（单位：毫秒)
			conn.setReadTimeout(30000); // 设置从主机读取数据超时（单位：毫秒)
			conn.setDoOutput(true); // post请求参数要放在http正文内，顾设置成true，默认是false
			conn.setDoInput(true); // 设置是否从httpUrlConnection读入，默认情况下是true
			conn.setUseCaches(false); // Post 请求不能使用缓存
			// 设定传送的内容类型是可序列化的java对象(如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
			conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			conn.setRequestMethod("POST");// 设定请求的方法为"POST"，默认是GET
			conn.setRequestProperty("Content-Length",requestUrl.length()+"");
			String encode = "utf-8";
			OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), encode);
			out.write(requestUrl.toString());
			out.flush();
			out.close();
			String result1 = getOut(conn);
			Debug.log("result=========返回的xml============="+result1);
			Map<String, String> orderMap = XMLUtil.doXMLParse(result1);
			
			Debug.log("orderMap==========================="+orderMap);
			//得到的预支付id
			String prepay_id = orderMap.get("prepay_id");
			
			
			SortedMap<String,String> params = new TreeMap<String,String>();
	        params.put("appId", config.APPID);
	        params.put("timeStamp",timestamp);
	        params.put("nonceStr", noncestr);
	        params.put("package", "prepay_id="+prepay_id);
	        params.put("signType", "MD5");
	        
	        //生成支付签名
	        String paySign =  reqHandler.createSign(params,productStoreId);

	        result.put("timeStamp", timestamp);
	        result.put("nonceStr", noncestr);
	        result.put("package", "prepay_id="+prepay_id);
	        result.put("signType", "MD5");
	        result.put("paySign", paySign);
	        
	        
			//后期要存表.每俩小时调用一次.
			String tokenParam = "grant_type=client_credential&appid="+config.APPID+"&secret="+config.APPSECRET;
			String tokenJsonStr = SendGET("https://api.weixin.qq.com/cgi-bin/token", tokenParam);
			Map tokenMap = JSON.parseObject(tokenJsonStr);
			//获取access_token
			String access_token = (String)tokenMap.get("access_token");
	        
			String ticketParam = "access_token="+access_token+"&type=jsapi";
			String ticketJsonStr = SendGET("https://api.weixin.qq.com/cgi-bin/ticket/getticket", ticketParam);
			Map ticketMap = JSON.parseObject(ticketJsonStr);
			//获取jsapi_ticket
			String ticket = (String)ticketMap.get("ticket");
			
	        String url = "http://www.51tequ.com/m";
			String signValue = "jsapi_ticket="+ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;
			Debug.log("url====="+signValue);
			String signature = Sha1Util.getSha1((signValue));
			result.put("signature", signature);
	        
		} catch (GenericEntityException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	
	public static Map<String, Object> getCoOrderWebPrepay(DispatchContext ctx, Map<String, ? extends Object> context) {
		Debug.log("createEcOrder   === start");
		Map<String, Object> result = ServiceUtil.returnSuccess();
		Delegator delegator = ctx.getDelegator();
		String orderId = (String)context.get("orderId");
		HttpServletRequest request = (HttpServletRequest)context.get("request");
		HttpServletResponse response = (HttpServletResponse)context.get("response");
		String noncestr = Sha1Util.getNonceStr();
		try {
			//付款金额
			String total_fee = "";
			String order_price = "";
			//产品ID 以及类型
			String product_name="";
			GenericValue orderHeader = null;
			if(!orderId.contains("PUR_")) {
				orderHeader = delegator.findOne("LetOrderHeader", UtilMisc.toMap("orderId", orderId),false);
			}else {
				orderHeader = delegator.findOne("LetPurchaseOrder", UtilMisc.toMap("orderId", orderId),false);
			}
			String productStoreId = orderHeader.getString("productStoreId");
			total_fee = String.valueOf(orderHeader.getBigDecimal("grandTotalAmount").doubleValue()*100);
			if(total_fee.contains(".")){
				order_price = total_fee.substring(0, total_fee.indexOf("."));
			}else{
				order_price = total_fee;
			}
			product_name = orderId;
			GzhConfig config = new GzhConfig(productStoreId);	
			
			RequestHandler reqHandler = new RequestHandler(request, response);
			 //初始化 
			reqHandler.init();
			reqHandler.init(config.APPID, config.APPSECRET, config.KEY, "");
			//执行统一下单接口 获得预支付id
			reqHandler.setParameter("appid",config.APPID);
			reqHandler.setParameter("mch_id", config.MCHID);                //商户号
			reqHandler.setParameter("nonce_str", noncestr);            //随机字符串
			if(product_name.length() > 30){
				product_name = product_name.substring(0, 30) + "..";
			}
			reqHandler.setParameter("body", product_name);                        //商品描述
			reqHandler.setParameter("out_trade_no", orderId);        //商家订单号
			reqHandler.setParameter("total_fee", order_price);                    //商品金额,以分为单位
			reqHandler.setParameter("spbill_create_ip",request.getRemoteAddr());   //用户的公网ip  IpAddressUtil.getIpAddr(request)
			//下面的notify_url是用户支付成功后为微信调用的action
			reqHandler.setParameter("notify_url", config.WEB_NOTIFY_URL);
			reqHandler.setParameter("trade_type", "NATIVE");
			//订单开始
			Date now=new Date();
		    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		    String time_start=dateFormat.format(now);
			reqHandler.setParameter("time_start", time_start);
			//订单结束时间
			String time_expire= getHalfHourAgoTime(5,"yyyyMMddHHmmss");
			reqHandler.setParameter("time_expire", time_expire);
			
			//------------需要进行用户授权获取用户openid-------------
			String requestUrl = reqHandler.getRequestURL("");
			Debug.log("requestUrl==================="+requestUrl);
			//统一下单接口提交  xml格式
			URL orderUrl = new URL("https://api.mch.weixin.qq.com/pay/unifiedorder");
			HttpURLConnection conn = (HttpURLConnection) orderUrl.openConnection();
			conn.setConnectTimeout(30000); // 设置连接主机超时（单位：毫秒)
			conn.setReadTimeout(30000); // 设置从主机读取数据超时（单位：毫秒)
			conn.setDoOutput(true); // post请求参数要放在http正文内，顾设置成true，默认是false
			conn.setDoInput(true); // 设置是否从httpUrlConnection读入，默认情况下是true
			conn.setUseCaches(false); // Post 请求不能使用缓存
			// 设定传送的内容类型是可序列化的java对象(如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
			conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			conn.setRequestMethod("POST");// 设定请求的方法为"POST"，默认是GET
			conn.setRequestProperty("Content-Length",requestUrl.length()+"");
			String encode = "utf-8";
			OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), encode);
			out.write(requestUrl.toString());
			out.flush();
			out.close();
			String json = getOut(conn);
			Debug.log("result=========返回的xml============="+json);
			Map<String, String> orderMap = XMLUtil.doXMLParse(json);
			
			Debug.log("orderMap==========================="+orderMap);
			//得到的预支付id
			String prepay_id = orderMap.get("prepay_id");
			String code_url = orderMap.get("code_url");
			result.put("orderId", orderId);
			result.put("code_url", code_url);
			Debug.log("prepay_id====="+prepay_id);	
			Debug.log("code_url====="+code_url);	
			} catch (UnsupportedEncodingException e) {
				Debug.logError(e.getMessage(), module);
			} catch (Exception e) {
				Debug.logError(e.getMessage(), module);
			}
		return result;
	}
	
	/**
	 * 异步返回
	 */
	public static String wxOrderNotify(HttpServletRequest request, HttpServletResponse response){
        try {
        	Delegator delegator = (Delegator) request.getAttribute("delegator");
        	LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    		InputStream inStream = request.getInputStream();
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
			    outSteam.write(buffer, 0, len);
			}
			outSteam.close();
			inStream.close();
			String resultStr  = new String(outSteam.toByteArray(),"utf-8");
			Map<String, String> resultMap = XMLUtil.doXMLParse(resultStr);
			Debug.log("resultMap===wxOrderNotify===================="+resultMap);
			String out_trade_no = resultMap.get("out_trade_no");
			String transaction_id = resultMap.get("transaction_id");
			String return_code = resultMap.get("return_code");
			GenericValue orderHeader = null;
			if(!out_trade_no.contains("PUR_")) {
				orderHeader = delegator.findOne("LetOrderHeader", UtilMisc.toMap("orderId", out_trade_no),false);
			}else {
				orderHeader = delegator.findOne("LetPurchaseOrder", UtilMisc.toMap("orderId", out_trade_no),false);
			}
			GenericValue userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", "admin"),false);
			String productStoreId = orderHeader.getString("productStoreId");
			GenericValue productStore = delegator.findOne("LetStore", UtilMisc.toMap("productStoreId", productStoreId),false);
			String statusId = orderHeader.getString("statusId");
			if(return_code.equals("SUCCESS")){
				if(UtilValidate.isNotEmpty(orderHeader) && "ORDER_CREATED".equals(statusId)){
					orderHeader.set("statusId", "ORDER_APPROVED");
					orderHeader.set("paymentStatusId", "INVOICE_RECEIVED");
					orderHeader.set("transactionId", transaction_id);
					orderHeader.store();
			        //充值流水
					List<GenericValue> coAccountList = delegator.findByAnd("CoAccountAndPerson", UtilMisc.toMap(
							"partyId", productStore.getString("companyId"),"accountTypeId","FINANCE_TYPE"), null, false);
					
					GenericValue coAccount = EntityUtil.getFirst(coAccountList);
					
					dispatcher.runSync("createRechargeHistory", UtilMisc.toMap("accountId", 
							coAccount.getString("accountId"),"paymentTypeId","PT_RECHARGE","paymentDetailId","SALE_INCOME",
							"amount",orderHeader.getBigDecimal("grandTotalAmount"),"statusId","WITH_END",
							"remark","企业下单","externalHistoryId",orderHeader.getString("orderId"),
							"isCheck","Y","userLogin",userLogin));
					
				}
			}
			request.setAttribute("out_trade_no", out_trade_no);
			response.getWriter().write(RequestHandler.setXML("SUCCESS", ""));
		} catch (UnsupportedEncodingException e) { 
			Debug.logError(e.getMessage(), module);
		} catch (IOException e) {
			Debug.logError(e.getMessage(), module);
		} catch (JDOMException e) {
			Debug.logError(e.getMessage(), module);
		} catch (GenericEntityException e) {
			Debug.logError(e.getMessage(), module);
		} catch (GenericServiceException e) {
			Debug.logError(e.getMessage(), module);
		}
		return "success";
	}
	
	public static String SendGET(String url,String param){
		   String result="";//访问返回结果
		   BufferedReader read=null;//读取访问结果
		   try {
		    //创建url
		    URL realurl=new URL(url+"?"+param);
		    //打开连接
		    URLConnection connection=realurl.openConnection();
		     // 设置通用的请求属性
		             connection.setRequestProperty("accept", "*/*");
		             connection.setRequestProperty("connection", "Keep-Alive");
		             connection.setRequestProperty("user-agent",
		                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		             //建立连接
		             connection.connect();
		             read = new BufferedReader(new InputStreamReader(
		                     connection.getInputStream(),"UTF-8"));
		             String line;//循环读取
		             while ((line = read.readLine()) != null) {
		                 result += line;
		             }
		   } catch (IOException e) {
			   Debug.logError(e.getMessage(), module);
		   }finally{
		    if(read!=null){//关闭流
		     try {
		      read.close();
		     } catch (IOException e) {
		    	 Debug.logError(e.getMessage(), module);
		     }
		    }
		   }
		     
		   return result; 
	}
	
	public static String getOut(HttpURLConnection conn) throws IOException{
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return null;
        }
        // 获取响应内容体
        BufferedReader in = new BufferedReader(new InputStreamReader(
                conn.getInputStream(), "UTF-8"));
        String line = "";
        StringBuffer strBuf = new StringBuffer();
        while ((line = in.readLine()) != null) {
            strBuf.append(line).append("\n");
        }

        in.close();
        return  strBuf.toString().trim();

	}
	
    public static String getHalfHourAgoTime (int minute,String nowTimeType) {
 	   if(UtilValidate.isEmpty(nowTimeType))nowTimeType = "yyyy-MM-dd HH:mm:ss";
   	   String halfHourTime = "";
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MINUTE, cal.get(Calendar.MINUTE)+minute);
        halfHourTime = new SimpleDateFormat(nowTimeType)
                .format(cal.getTime());
        return halfHourTime;
   }
}
